package cn.com.sassali.dynamic;

import cn.com.sassali.service.IUserService;
import cn.com.sassali.service.impl.UserService;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @ClassName CglibDynamicProxyFactory
 * @Description     cglib 动态代理工厂类
 * @Author lujiansen
 * @date 2020/4/26 9:05 下午
 */
public class CglibDynamicProxyFactory {

    public static Enhancer enhancer = new Enhancer();
    public static Enhancer enhancerAnonymous = new Enhancer();
    public static CglibMethodInterceptor interceptor = new CglibMethodInterceptor();

    public static IUserService newInstance() {
        // 设置父类
        enhancer.setSuperclass(UserService.class);
        // 设置方法调用
        enhancer.setCallback(interceptor);
        return (IUserService) enhancer.create();
    }

    public static IUserService newInstanceAnonymous() {
        // 设置父类
        enhancerAnonymous.setSuperclass(UserService.class);
        // 设置方法调用
        enhancerAnonymous.setCallback(new MethodInterceptor() {
            // @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                System.out.println("开始CGLib动态代理 anonymous === ");
                Object object = proxy.invokeSuper(obj, args);
                System.out.println("结束CGLib动态代理 anonymous === ");
                return object;
            }
        });
        return (IUserService) enhancerAnonymous.create();
    }



}
